package org.ucas.faker.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.ucas.faker.web.dto.CarryDto;
import org.ucas.faker.web.entity.User;
import org.ucas.faker.web.exceptions.ForbiddenException;
import org.ucas.faker.web.service.UserService;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by suemi on 17-7-1.
 */
@Controller
public class UserController extends BaseController {

  @Autowired
  private UserService userService;

  @RequestMapping(value = "/users/all", method = RequestMethod.GET)
  @ResponseBody
  public List<User> listAllUsers(){
    return new ArrayList<>();
  }

  @RequestMapping(value = "/login.html", method = RequestMethod.GET)
  public ModelAndView login() {
 //   if(currentUserId() !=null)
 //     return new ModelAndView(new RedirectView("/", true));

    return new ModelAndView("/user/login");
  }

  @RequestMapping(value = "/logout.html", method = RequestMethod.GET)
  public ModelAndView logout() {
//    if(currentDepotId() != null) refreshSelect();
    context().depotId = null;
    context().userId = null;
    return new ModelAndView(new RedirectView("/login.html", true));
  }
  @ResponseBody
  @RequestMapping(value = "/users/login", method = RequestMethod.POST)
  public CarryDto<String> login(@RequestParam(value = "account") String userName,
                            @RequestParam(value = "password") String password) {
	System.out.println("userName: "+userName);
    User user = userService.findByAccount(userName);
    String msg = "";
    if(user == null){
      msg="此用户不存在";
    }else if(user.getPassword().equals(password)) {
      context().userId = user.getId();
      msg="用户已登陆";
    } else {
    	msg="用户名密码不匹配";
    }
    return CarryDto.of(msg);
  }


//  @RequestMapping(value = "/users/create.html", method = RequestMethod.GET)
//  public ModelAndView createUser() {
//    User me = currentUser();
//    if(me == null || !"root".equals(me.getAccount()))
//      throw ForbiddenException.FORBIDDEN;
//
//    ModelAndView view = new ModelAndView("user/create");
//    view.addObject("user",currentUser());
//    return view;
//  }
  @ResponseBody
  @RequestMapping(value = "/users/register", method = RequestMethod.POST)
  public CarryDto<String> register(User user) {
	  System.out.println(user.getAccount());
//    User me = currentUser();
    String msg = null;
//    if(me == null || !"root".equals(me.getAccount()))
//      msg = "您无此权限创建用户";
    
    if(msg == null) msg = userService.createUser(user);
    if(msg == null) msg = "创建成功！";
//    ModelAndView view = new ModelAndView("/user/create");
//    view.addObject("user",currentUser());
//    view.addObject("msg",msg);
    System.out.println(msg);
    return CarryDto.of(msg);
  }


}
